package com.iotechn.unimall.admin.api.distribution;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.iotechn.unimall.biz.service.distribution.DistributionBizService;
import com.iotechn.unimall.core.exception.AdminServiceException;
import com.iotechn.unimall.core.exception.AppServiceException;
import com.iotechn.unimall.core.exception.ExceptionDefinition;
import com.iotechn.unimall.core.exception.ServiceException;
import com.iotechn.unimall.data.domain.DistributionBalanceDetailDO;
import com.iotechn.unimall.data.domain.DistributionDO;
import com.iotechn.unimall.data.dto.DistributionRankingDTO;
import com.iotechn.unimall.data.mapper.DistributionBalanceDetailMapper;
import com.iotechn.unimall.data.mapper.DistributionMapper;
import com.iotechn.unimall.data.model.Page;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: rize
 * Date: 2019/11/27
 * Time: 11:22
 */
@Service
public class AdminDistributionServiceImpl implements AdminDistributionService {

    @Autowired
    private DistributionMapper distributionMapper;

    @Autowired
    private DistributionBalanceDetailMapper distributionBalanceDetailMapper;

    @Autowired
    private DistributionBizService distributionBizService;

    @Override
    public String create(Long userId, Integer level, Long parentUserId, Integer status, String realname, String idCard, Integer allowChild, String phone, Long adminId) throws ServiceException {
        Integer count = distributionMapper.selectCount(new EntityWrapper<DistributionDO>().eq("user_id", userId));
        if (count > 0) {
            throw new AdminServiceException(ExceptionDefinition.DISTRIBUTION_USER_IS_THE_MEMBER);
        }
        if ((level == 1 && parentUserId != 0) || ((level == 3 || level == 2) && parentUserId == 0)) {
            throw new AdminServiceException(ExceptionDefinition.DISTRIBUTION_LEVEL_LOGIC_ERROR);
        }
        if (allowChild == 1 && level > 2) {
            throw new AdminServiceException(ExceptionDefinition.DISTRIBUTION_THIRD_LEVEL_CANNOT_ALLOW_CHILD);
        }
        Long parentId = null;
        if (parentUserId != null && parentUserId != 0) {
            List<DistributionDO> parentList = distributionMapper.selectList(new EntityWrapper<DistributionDO>().eq("user_id", parentUserId));
            if (CollectionUtils.isEmpty(parentList)) {
                throw new AdminServiceException(ExceptionDefinition.DISTRIBUTION_PARENT_USER_IS_NOT_DISTRIBUTOR);
            }
            parentId = parentList.get(0).getId();
        } else {
            parentId = 0l;
        }
        Date now = new Date();
        DistributionDO distributionDO = new DistributionDO();
        distributionDO.setUserId(userId);
        distributionDO.setLevel(level);
        distributionDO.setParentId(parentId);
        distributionDO.setRealname(realname);
        distributionDO.setIdCard(idCard);
        distributionDO.setPhone(phone);
        distributionDO.setBalance(0);
        distributionDO.setFreezeBalance(0);
        distributionDO.setStatus(status);
        distributionDO.setGmtCreate(now);
        distributionDO.setGmtUpdate(now);
        distributionDO.setAllowChild(allowChild);
        if (distributionMapper.insert(distributionDO) > 0) {
            return "ok";
        }
        throw new AdminServiceException(ExceptionDefinition.DISTRIBUTION_UNKNOWN_EXCEPTION);
    }

    @Override
    public String edit(Long distributionId, Integer status, String realname, String idCard, Integer allowChild, String phone, Long adminId) throws ServiceException {
        Integer count = distributionMapper.selectCount(new EntityWrapper<DistributionDO>().eq("id", distributionId));
        if (count <= 0) {
            throw new AdminServiceException(ExceptionDefinition.DISTRIBUTION_NOT_EXIST);
        }
        Date now = new Date();
        DistributionDO distributionDO = new DistributionDO();
        distributionDO.setId(distributionId);
        distributionDO.setRealname(realname);
        distributionDO.setIdCard(idCard);
        distributionDO.setPhone(phone);
        distributionDO.setGmtUpdate(now);
        distributionDO.setStatus(status);
        distributionDO.setAllowChild(allowChild);
        if (distributionMapper.updateById(distributionDO) > 0) {
            return "ok";
        }
        throw new AdminServiceException(ExceptionDefinition.ADMIN_UNKNOWN_EXCEPTION);
    }


    @Override
    public Page<DistributionDO> list(Integer page, Integer limit, Integer level, String realname, String idCard, String phone, Long userId, String orderBy, Long adminId) throws ServiceException {
        Wrapper<DistributionDO> wrapper = new EntityWrapper<>();
        if (userId != null) {
            wrapper.eq("user_id", userId);
        }
        if (level != null) {
            wrapper.eq("level", level);
        }
        if (!StringUtils.isEmpty(idCard)) {
            wrapper.eq("id_card", idCard);
        }
        if (!StringUtils.isEmpty(phone)) {
            wrapper.eq("phone", phone);
        }
        if (!StringUtils.isEmpty(realname)) {
            wrapper.like("realname", realname);
        }
        if ("totalSum".equals(orderBy)) {
            wrapper.orderBy("total_sum", false);
        }
        Integer count = distributionMapper.selectCount(wrapper);
        List<DistributionDO> distributionDOS = distributionMapper.selectPage(new RowBounds((page - 1) * limit, limit), wrapper);
        return new Page<>(distributionDOS, page, limit, count);
    }

    @Override
    public String delete(Long distributionId, Long adminId) throws ServiceException {
        if (distributionMapper.deleteById(distributionId) > 0) {
            return "ok";
        }
        throw new AdminServiceException(ExceptionDefinition.DISTRIBUTION_UNKNOWN_EXCEPTION);
    }

    @Override
    public Page<DistributionRankingDTO> rankingList(Integer page, Integer limit, Long adminId) throws ServiceException {
        return distributionBizService.getRankingPage(page, limit);
    }

    @Override
    public Page<DistributionBalanceDetailDO> detailPage(Long distributionId, Integer page, Integer limit, Long adminId) throws ServiceException {
        Wrapper<DistributionBalanceDetailDO> wrapper = new EntityWrapper<DistributionBalanceDetailDO>();
        wrapper.eq("distribution_id", distributionId);
        wrapper.orderBy("id", false);
        List<DistributionBalanceDetailDO> detailDOS = distributionBalanceDetailMapper.selectPage(new RowBounds((page - 1) * limit, limit), wrapper);
        Integer count = distributionBalanceDetailMapper.selectCount(wrapper);
        return new Page<>(detailDOS, page, limit, count);
    }
}
